package org.custom.spring.boot.datasource.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import org.custom.spring.boot.datasource.service.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

/**
 * DruidDataSourceBuilder
 *
 * @author 李坤
 * @date 2022/3/31 15:36
 */
@Service("druidDataSourceBuilder")
public class DruidDataSourceBuilder implements DataSourceBuilder {
    @Override
    public Class<? extends DataSource> getSupportDataSource() {
        return DruidDataSource.class;
    }

    @Override
    public DataSource generateDataSource(DataSourceProperties dataSourceProperties) {
        // 构建 DruidDataSource 对象服务
        DruidDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(DruidDataSource.class).build();

        // 设置最大等待时长
        dataSource.setMaxWait(1000);
        // 连接失败后中断无限重连
        dataSource.setBreakAfterAcquireFailure(true);
        // 设置数据源连接失败重连次数
        dataSource.setConnectionErrorRetryAttempts(2);

        return dataSource;
    }
}
